<?php
namespace App\Http\Controllers\Bid;

use App\Http\Controllers\BaseController;
use App\Http\Models\Biding;
use App\Http\Models\Total;

use Request;
use DB;
class BidController extends BaseController{


    public function test(){

        $one = DB::table('biding_record')->where(['bid_id'=>387])->min('price');
        echo $one;

    }


    //状态标书列表 0竞价中，1已中标，2未中标，3流拍，4效益作废，5拒收，6待确认，7成交
    public function statusBidList(){
        $request  = $this->requestAll();
        $redis = $this->redis();
        $userInfo =[];
        if(!empty($request['user_token'])){
            $userInfo = $this->getUserInfo();
        }
        $request['user_type'] = $userInfo['user_type'];
        $request['user_id'] = $userInfo['user_id'];
        $request['bid_status'] = tabBidStatusDataMap($request['tab']);

        $bid = new Biding();
        //招标中 数据
        $bidList = $bid->getBidListByStatus($request);
        //数据格式化
        foreach ($bidList as $k =>$v){
            if(!empty($v)){
                //项目备注显示隐藏
                $bidList[$k]['show_remark'] =false;
                $bidList[$k]['show_remark_ud'] = '../../../img/index/up.png';
                //时间
                $bidList[$k]['time'] = date('m-d',strtotime($v['bid_start_time']));
                //发布者
                $bidList[$k]['bid_user_company'] =companyNameFilter($bidList[$k]['bid_user_company']);
                //项目类型
                $bidList[$k]['bid_type'] =bidTypeDataMap($bidList[$k]['bid_type']);
                //城市
                $bidList[$k]['city_id'] =cityDataMap($bidList[$k]['city_id']);
            }

        }



        $this->jsonResult(200,$bidList);

    }

    //发布标书初始化页面
    public function pushBidInit(){
        $request  = $this->requestAll();
        $userInfo = $this->getUserInfo();
        //未认证
        if($userInfo['user_type'] == 0){
            $this->jsonResult(211,'','未认证,跳转到认证页面！');

        }
        // 是供应商
        if($userInfo['user_type'] == 11) {
            $this->jsonResult(212,'','您是供应商，可参与竞价');

        }
        //医院 审核中
        if($userInfo['user_type'] == 10 && $userInfo['user_status'] == 1) {
            $this->jsonResult(213,'','审核中，请稍后...');

        }
        //医院 ，驳回
        if($userInfo['user_type'] == 10 && $userInfo['user_status'] == 3) {
            $this->jsonResult(214,'','审核驳回，请联系客服');

        }
        // 可发布竞价客户
        if($userInfo['user_type'] == 10 && $userInfo['user_status'] == 2) {
            $clm1 =[];$clm2 =[];$clm3 =[];$provinceList=[];
            $userInfo['area'] = provinceDataMap($userInfo['province_id']).' '.cityDataMap($userInfo['city_id']).' '.areaDataMap($userInfo['area_id']);

            $bidType = bidTypeDataMap();//分类类型
            $arrTime = bidArrivalTimeDataMap();//交货时间
            $payType = bidPayTypeDataMap();//付款方式
            $pro =  provinceDataMap();//省列表
            foreach ($bidType as $k => $v){
                $clm1[] =array('text'=> $v,'value'=>$k);
            }
            foreach ($arrTime as $k => $v){
                $clm2[] =array('text'=> $v,'value'=>$k);

            }
            foreach ($payType as $k => $v){
                $clm3[] =array('text'=> $v,'value'=>$k);
            }

            foreach ($pro as $k => $v){
                $provinceList[] =array('text'=> $v,'value'=>$k);
            }

            $userInfo['column1'] = $clm1;
            $userInfo['column2'] = $clm2;
            $userInfo['column3'] = $clm3;
            $userInfo['provinceList'] = $provinceList;


            $this->jsonResult(200,$userInfo,'审核通过');

        }else{
            $this->jsonResult(500,'','系统错误,请联系客服');

        }
    }

    //发布标书
    public function pushBid(){
        $requestAll  = $this->requestAll();
        $request = $requestAll['formData'];
        $data=[];
        $goods =$request['addPro'];
        //获取用户信息
        $user = $this->getUserInfo($request);
        //项目名称
        $bidName = '采购'.bidTypeDataMap($request['bid_type']);
        foreach ($goods as $k=>$v){
            $bidName .= '-'.$v['goods_name'];
        }

        $data = [
            'bid_name'=>$bidName,
            'bid_sn'=>create_sn(),

            'bid_type'=>isset($request['bid_type'])?$request['bid_type']:0,//标书分类
            'bid_post_addr'=>isset($request['bid_post_addr'])?$request['bid_post_addr']:'',//收货地址
            'bid_contact_man'=>isset($request['bid_contact_name'])?$request['bid_contact_name']:'',//联系人
            'bid_contact_phone'=>isset($request['bid_contact_phone'])?$request['bid_contact_phone']:'',//联系电话
            'bid_arrival_time'=>isset($request['bid_arrival_time'])?$request['bid_arrival_time']:0,//交货时间
            'bid_budget'=>isset($request['bid_budget'])?$request['bid_budget']:0,//预算
            'bid_pay_type'=>isset($request['bid_pay_type'])?$request['bid_pay_type']:0,//付款方式
            'bid_remark'=>isset($request['bid_remark'])?$request['bid_remark']:'',//备注

            'province_id'=>$request['province_id'],
            'city_id'=>$request['city_id'],
            'area_id'=>$request['area_id'],

            'bid_user_id'=>$user['user_id'],
            'bid_user_company'=>$user['company_name'],
            'bid_start_time'=>bidStartTime(), //竞标开始时间
            'bid_status'=>20  //已发布

        ];
        $res = DB::table('biding')->insertGetId($data);
        foreach ($goods as $k=>$v){
            $goods[$k]['bid_id'] = $res;
            $goods[$k]['user_id'] = $user['user_id'];
            if(empty($v['goods_remark'])){
                $goods[$k]['goods_remark'] = '';

            }

        }
        //保存商品
        $r = DB::table('biding_goods')->insert($goods);

        //统计计算
        $total = new Total;
        $total->pushBidTotal($data);
        $this->jsonResult(200,array('bid_id'=>$res));
    }

    //投标报名
    public function enrollBid(){
        $request = $this->requestAll();
        $bidId = $request['bid_id'];
        $userInfo  = $this->getUserInfo(); //通过
        $bidInfo = DB::table('biding')->where('bid_id',$request['bid_id'])->first();
        //如果 user_type ==0 去认证
        if($userInfo['user_type'] == 0){
            $this->jsonResult(201,'','未认证,跳转到认证页面！');
        }
        //如果 user_type ==10 医院用户，不能报名
        if($userInfo['user_type'] == 10){
            $this->jsonResult(202,'','您是采购方，可以发布竞价！');
        }
        //如果 user_type ==11 ， 审核中
        if($userInfo['user_type'] == 11 && $userInfo['user_status'] == 1){
            $this->jsonResult(203,'','审核中，请稍后...');
        }
        //如果 user_type ==11 ， 审核驳回
        if($userInfo['user_type'] == 11 && $userInfo['user_status'] == 3){
            $this->jsonResult(204,'','审核驳回，请联系客服');
        }
        //如果报名已开始
        if(now() > $bidInfo['bid_start_time']){
            $this->jsonResult(205,'','竞价开始了，您来晚了');

        }
        if($userInfo['user_type'] == 11 && $userInfo['user_status'] == 2) {
            $re = DB::table('biding_enlist')->where(['bid_id' => $bidId, 'user_id' => $userInfo['user_id']])->first();
            if (empty($re)) {
                $data = [
                    'bid_id' => $bidId,
                    'user_id' => $userInfo['user_id']
                ];
                DB::table('biding_enlist')->insert($data);
                //订单参与人数+1
                DB::table('biding')->where('bid_id', $bidId)->increment('bid_enlist_num');

            }

            $this->jsonResult(200);
        }else{
            $this->jsonResult(500,'','系统错误,请联系客服');

        }

    }
    //获取跳转页面
    public function getGoWhere(){
        $request = $this->requestAll();
        $bid = new Biding();
        if(!empty($request['user_token'])){
            $userInfo = $this->getUserInfo(); //通过 user_token 获取userinfo

            $request['user_id']  = $userInfo['user_id']; //通过 user_token
            $request['user_type'] = $userInfo['user_type'];

        }else{
            //未登录
            $request['user_id']  = 0;
            $request['user_type'] = 0;
        }


        $data = $bid->goWhere($request);


        $this->jsonResult(200,$data);

    }


    //标书详情
    public function getBidDetail(){
        $request = $this->requestAll();
        $bid = new Biding();

        if(!empty($request['user_token'])){
            $userInfo = $this->getUserInfo(); //通过 user_token 获取userinfo

            $request['user_id']  = $userInfo['user_id']; //通过 user_token
            $request['user_type'] = $userInfo['user_type'];

        }else{
            //未登录
            $request['user_id']  = 0;
            $request['user_type'] = 0;
        }
        

        $didDetail = $bid->getBidById($request);

        //用户是否报名

        $this->jsonResult(200,$didDetail);


    }

    //报价
    public function pushPrice(){
        $request = $this->requestAll();
        $request['user_id']  = $this->userInfo($request['user_token'],'user_id'); //通过 user_token 获取用户id 比较安全

        $bid = new Biding();
        $re  = $bid->getBidById($request);


        if($request['price'] <= 0){
            $this->jsonResult(301,'','报价金额不正确！');
        }
        if($re['isEnroll'] !=1){
            $this->jsonResult(301,'','您没有报名！');
        }

        if($re['bidChangeStatus'] != $request['rotation']*10){
            $this->jsonResult(301,'','本轮报价已结束，请进行下一轮报价！');
        }
        if($re['is_pushPrice'] != 0){
            $this->jsonResult(301,'','本轮已报价，请等待下一轮报价！');
        }
        //大当前可报最高报价
        if($request['price'] > $re['now_mixPush']){
            $this->jsonResult(301,'','当前最低报价：'.$re['now_minPrice'].',下一次报价至少要小于等于：￥'.$re['now_mixPush'].'元');
        }
        
        $data = [
            'bid_id'=>$request['bid_id'],
            'user_id'=>$request['user_id'],
            'price'=>$request['price'],
            'rotation'=>$request['rotation'],
            'user_company'=> companyNameDataMap($request['user_id']),

        ];
        DB::table('biding_record')->insertGetId($data);

        $this->jsonResult(200);

    }
    //医院供应商确认
    public function isTrue(){
        $request = $this->requestAll();
        $data =[];
        $total = new Total;
        $bid = DB::table('biding')->where('bid_id',$request['bid_id'])->first();
        $data['bid_status']=$bid['bid_status'];
        if($bid['bid_status'] == 28){
            $data['bid_status']=29;
            //医院点击确认 统计计算
            $total->buyerTrueTotal($bid);


        }
        //待供应商确认 ，70已完成
        if($bid['bid_status'] == 29){
            $data['bid_status']=70;
            //供应商 统计计算
            $total->sellerTrueTotal($bid);

        }
        $res = DB::table('biding')->where('bid_id',$request['bid_id'])->update($data);
        if($res >0 && $data['bid_status']==29){
            //发送短信通知供应商
            if(!empty($bid['pick_user_id'])){
                $pickUser = DB::table('user')->where('user_id',$bid['pick_user_id'])->first();
                $content = '【医竞采】恭喜，'.$pickUser['company_name'].'，您参与的'.$bid['bid_name'].'项目，采购方已确认，请尽快发货，如有疑问，请联系客服！';
                $this->bidSendSms($pickUser['user_phone'],$content);
            }


        }


        $this->jsonResult(200);

    }
    //医院确认
    public function buyerIsTrue(){

    }
    //供应商确认
    public function sellerIsTrue(){


    }
}
